/**
 * Created by WT-SUN on 2017/5/8.
 */
var recordTb_lastIndex='lastIndex';
$(function () {
    $('#recordTb').datagrid({
        view: detailview,
        rownumbers: true,//显示行号
        striped: true,
        fit: true,
        singleSelect: true,
        sortOrder: true,
        fitColumns: true,
        pagination: true,
        toolbar: '#toolbar',
        url: ROOT_PATH + '/train/plan/TrainTable.shtml',
        queryParams: {
            sort: 'addTime',
            order: 'desc'
        },
        detailFormatter:function(index,row){
            return '<div class="taskddv" style="padding:5px"></div>';
        },
        onCollapseRow:function(index,row){
            var ddv = $('#recordTb').datagrid('getRowDetail', index).find('table.tbddv');
            ddv.datagrid('clearSelections');
        },
        onExpandRow: function(index,row){
            $('.taskddv').html('');
            if (recordTb_lastIndex!='lastIndex'&&recordTb_lastIndex!=index){
                $('#recordTb').datagrid('collapseRow',recordTb_lastIndex);
                $('.taskddv').empty();
            }
            var htmlTb='<table id="taskDivTb" class="tbddv"></table>';
            $('.taskddv').append(htmlTb);
            var ddv = $('#recordTb').datagrid('getRowDetail', index).find('table.tbddv');
            ddv.datagrid({
                url: ROOT_PATH + '/train/record/selectByPlanId.shtml',
                queryParams: {
                    planId: row.id,
                },
                fitColumns: true,
                striped: true,
                singleSelect: true,
                rownumbers: true,
                loadMsg: '',
                height: 'auto',
                columns: [[
                    {
                        field: 'id',
                        checkbox: true
                    },
                    {
                        field: 'planId', hidden:true, title: '业务Id', hidden:true,width: 20
                    },
                    {field: 'year', title: '年度', width: 80},
                    {field: 'rName', title: '培训班名称', width: 130,formatter:function (value, row, index) {
                        return "<a href='javascript:void(0)' class='easyui-linkbutton text-primary' plain='true'   onclick='infoRecord(\""+row.id+"\",\""+row.planId+"\");'>"+row.rName+"</a>";
                    }},
                    {field: 'peInfo', title: '人员信息', width: 130,formatter:function (value, row, index) {
                        return "<a href='javascript:void(0)' class='easyui-linkbutton text-primary' plain='true'   onclick='infoUser(\""+row.id+"\");'>人员</a>";
                    }},
                    {field: 'actualStartTime', title: '实际开班日期', width: 130},
                    {field: 'trainContent', title: '培训班内容', width: 200},
                    {field: 'actualTrainHour', title: '实际培训学时', width: 130},
                    {field: 'planTrainPerson', title: '计划人数', width: 100},
                    {field: 'realHgUserNum', title: '合格人数', width: 100},
                    {field: 'realNhUserNum', title: '不合格人数', width: 100},
                    {field: 'trainTeacher', title: '培训教师', width: 100},
                    {field: 'trainFormName', title: '培训形式', width: 100},
                    {field: 'deptName', title: '登记部门', width: 100}
                ]],
                onLoadSuccess: function () {
                    recordTb_lastIndex=index;
                    $('#recordTb').datagrid('fixDetailRowHeight',index);
                }
            });
            $('#recordTb').datagrid('fixDetailRowHeight',index);
        },
        columns: [[
            {
                field: 'id',hidden:true
            },
            {field: 'name', title: '培训班名称', width: 150, sortable: true},
            {field: 'planTrainPeriod', title: '计划举办期数', width: 130},
            {field: 'realPeNum', title: '实际举办期数', width: 130},
            {field: 'hourNum', title: '实际培训学时', width: 130},
            {field: 'planTrainPerson', title: '计划培训人数', width: 130},
            {field: 'realUserNum', title: '实际培训人数', width: 130},
            {field: 'realHgUserNum', title: '合格人数', width: 100},
            {field: 'realNhUserNum', title: '不合格人数', width: 100},
            {field: 'planTypeIdName', title: '计划分类', width: 100},
            {field: 'proTypeIdName', title: '专业类别', width: 100},
            {field: 'trainLevelIdName', title: '培训级别', width: 100},
            {field: 'hostDeptNamea', title: '主办单位', width: 100, formatter: function (value, row, index) {
                return row.isExternal == '0' ? row.hostDeptIdName : row.hostDeptName;
            }},
            {
                field: 'hasCertificate', title: '是否取证', width: 100, formatter: function (value, row, index) {
                return row.hasCertificate == '0' ? '不是' : '是';
            }
            },
            {field: 'realName', title: '登记人', width: 100},
            {field: 'deptName', title: '登记部门', width: 100},
            {field: 'addTime', title: '登记时间', width: 100}
        ]]
    });
    $('#btn_tr_record_add').on('click',function () {
        addRecord();
    });
    $('#btn_tr_record_delete').on('click',function () {
        deleteRecord();
    });
    $('#btn_tr_record_edit').on('click',function () {
        editRecord();
    });
    $('#btn_advanced_search').on("click", function () {
        $('#queryForm2').toggle();
        $('#recordTb').datagrid('resize');
    });
    $('#btn_clear').on("click", function () {
        $('#queryForm1').form('reset');
        $('#queryForm2').form('reset');
    });
    var TRAIN_PLANTYPE=CONSTANT.DictionaryTypeDefConstants.TRAIN_PLANTYPE;//记录分类标识
    queryComboData(TRAIN_PLANTYPE,'planTypeId');
    var TRAIN_TRAINTYPE=CONSTANT.DictionaryTypeDefConstants.TRAIN_TRAINTYPE;//培训类别标识
    queryComboData(TRAIN_TRAINTYPE,'trainTypeId');
    var TRAIN_PROTYPE=CONSTANT.DictionaryTypeDefConstants.TRAIN_PROTYPE;//专业类别标识
    queryComboData(TRAIN_PROTYPE,'professionalTypeId');
    var TRAIN_LEVEL=CONSTANT.DictionaryTypeDefConstants.TRAIN_LEVEL;//培训级别标识
    queryComboData(TRAIN_LEVEL,'trainLevelId');
    var stateData=[{id:'',text:'请选择'},{id:'0',text:'否'},{id:'1',text:'是'}];
    pageComData('isExternal',stateData);
    /**
     * 高级查询
     */
    /*
     var code=CONSTANT.DictionaryTypeDefConstants.OHE_FACILITY_TYPE;
     queryComboData(code,'#facilitieTypeQuery');
     queryDepartmentTree();*/
    /**
     * 绑定人员选择事件
     */
    $("#searchAddUser").textbox({
        iconWidth: 20,
        icons: [{
            iconCls: 'icon-add',
            handler: function(e){
                add_userId_func();
            }
        },{
            iconCls: 'icon-remove',
            handler: function(e){
                $(e.data.target).textbox('clear');

            }
        }]
    });
    queryDepartmentTree();
    /*planStartMonth("#planStartMonthMin");
     planStartMonth("#planStartMonthMax");*/
    queryYearthList("yearAnnual");
});

var add_userId_func = function () {
    WindowManager.openLayer({
        type: 2,
        title: '选择人员信息',
        area: ['1150px', '70%'],
        content: ROOT_PATH + '/permission/user/simpleList.shtml?isMulti=0',
        callBack:function(data){
            getSelectedUser(data);
        }
    });
};
/**
 * 人员信息选择
 */
var getSelectedUser = function (data) {
    $("#searchAddUser").textbox('setValue', data[0].id).textbox('setText', data[0].realName);
};
function queryDepartmentTree(){
    $.ajax({
        url:ROOT_PATH + '/permission/department/getDepartmentTree.shtml',//提交地址
        data:{parentId : 0},//将表单数据序列化
        type:"POST",
        dataType:"json",
        success:function(result){
            deptCom('searchAddDept',result);
        }
    });
}
function deptCom(id,result) {
    var deptId='#'+id;
    $(deptId).combotree(
        {
            data:result,
            require:true,
            prompt:'请选择',
            loadFilter:function(data){
                var newData = new Array();
                newData.push({id:"",text:'请选择'});
                newData.push(data[0]);
                return newData;
            }
        }
    );
}

function pageComData(id,data) {
    var pageId='#'+id;
    $(pageId).combobox({
        data: data,
        valueField: 'id',
        textField: 'text',
        editable: false,
        panelHeight: '200',
        selectOnNavigation:true,
    });
}
function queryComboData(code,queryId) {
    var EMPTY_OPTION = {
        id: '',
        text: '请选择'
    };
    var pageId='#'+queryId;
    $.ajax({
        type: 'post',
        url: ROOT_PATH + '/permission/dictionary/queryDictionaryByDictionaryTypeCode.shtml',
        data: {code: code},
        dataType: "json",
        success: function (result) {
            $(pageId).combobox({
                loadFilter: function (data) {
                    data.unshift(EMPTY_OPTION);
                    return data;
                },
                data: result,
                valueField: 'id',
                textField: 'text',
                editable: false,
                panelHeight: '200',
                onSelect: function (record) {
                }
            });
        }
    });
}
function planStartMonth(id) {
    $(id).datebox({
        onShowPanel: function () {//显示日趋选择对象后再触发弹出月份层的事件，初始化时没有生成月份层
            span.trigger('click'); //触发click事件弹出月份层
            if (!tds) setTimeout(function () {//延时触发获取月份对象，因为上面的事件触发和对象生成有时间间隔
                tds = p.find('div.calendar-menu-month-inner td');
                tds.click(function (e) {
                    e.stopPropagation(); //禁止冒泡执行easyui给月份绑定的事件
                    var year = /\d{4}/.exec(span.html())[0]//得到年份
                        , month = parseInt($(this).attr('abbr'), 10); //月份，这里不需要+1
                    $('#planStartMonth').datebox('hidePanel')//隐藏日期对象
                        .datebox('setValue', year + '-' + month); //设置日期的值
                });
            }, 0);
            yearIpt.unbind();//解绑年份输入框中任何事件
        },
        parser: function (s) {
            if (!s) return new Date();
            var arr = s.split('-');
            return new Date(parseInt(arr[0], 10), parseInt(arr[1], 10) - 1, 1);
        },
        formatter: function (d) {
            var a = parseInt(d.getMonth())<parseInt('9')?'0'+parseInt(d.getMonth()+ 1):d.getMonth() + 1;
            return d.getFullYear() + '-' +a; }
    });
    var p = $(id).datebox('panel'), //日期选择对象
        tds = false, //日期选择对象中月份
        yearIpt = p.find('input.calendar-menu-year'),//年份输入框
        span = p.find('span.calendar-text'); //显示月份层的触发控件
}
/**
 * 重新加载表格
 */
function reLoadData() {
    recordTb_lastIndex='lastIndex';
    $('#recordTb').datagrid('clearSelections');
    var queryParams1 = $('#queryForm1').serializeJson();
    var queryParams2 = $('#queryForm2').serializeJson();
    var queryParams = $.extend(queryParams1,queryParams2);
    queryParams["sort"] = 'addTime';
    queryParams["order"] = 'desc';
    $('#recordTb').datagrid('options').queryParams = queryParams;
    $("#recordTb").datagrid('reload', ROOT_PATH + '/train/plan/TrainTable.shtml');
}
function queryYearthList(id){
    var date = new Date();
    var year = date.getFullYear();
    var yearthData = new Array();
    yearthData.push({id:"",text:"请选择"});
    for(var i =0;i<6;i++){
        var y = {id:year-i,text:(year-i)+'年'};
        yearthData.push(y);
    }
    $('#'+id).combobox(
        {
            data:yearthData,
            valueField:'id',
            textField:'text'
        }
    );
}
/**
 * 打开弹框
 * @param title
 * @param content
 */
function openLayers(title, content) {
    WindowManager.openLayer({
        type: 2,
        resize: false,
        title: title,
        area: ['1150px', '80%'],
        content: content,
        callBack:function(data){
            if(data){
                reLoadData();
            }
        }
    });
}
/**
 * 打开新建
 */
function addRecord() {
    var title = '新增培训记录';
    var content = ROOT_PATH + '/train/record/add.shtml?resourceId=' + $.getQueryParam('resourceId');
    openLayers(title, content);
}
/**
 * 删除
 */
function deleteRecord() {
    if (recordTb_lastIndex!='lastIndex'){
        var ddv = $('#recordTb').datagrid('getRowDetail', recordTb_lastIndex).find('table.tbddv');
        var rows = ddv.datagrid('getSelections');
        if(rows.length==0){
            layer.alert("请选择计划下的培训记录进行删除！");
            return;
        }else {
            var id=rows[0].id;
            layer.confirm('是否确定撤销当前培训记录？', {
                btn: ['确定', '取消'] //按钮
            }, function () {
                $.ajax({
                    type: 'post',
                    url: ROOT_PATH + '/train/record/deleteById.shtml',
                    data: {id: id},
                    dataType: "json",
                    success: function (result) {
                        if (result.success) {
                            $('#recordTb').datagrid('clearSelections');
                            reLoadData();
                            layer.msg('删除成功', {
                                icon: 1,
                                time: 1000
                            });
                        }
                        else {
                            layer.msg('删除失败', {
                                icon: 2,
                                time: 1000
                            });
                        }
                    }
                });
            });
        }
    }else {
        layer.alert("请选择计划下的培训记录进行删除！");
        return;
    }
}
/**
 * 编辑
 */
function editRecord() {
    if (recordTb_lastIndex!='lastIndex'){
        var ddv = $('#recordTb').datagrid('getRowDetail', recordTb_lastIndex).find('table.tbddv');
        var rows = ddv.datagrid('getSelections');
        if(rows.length==0){
            layer.alert("请选择计划下的培训记录进行编辑！");
            return;
        }else {
            var id = rows[0].id;
            var planId=rows[0].planId;
            var title = '编辑培训记录';
            var content = ROOT_PATH + '/train/record/info.shtml?resourceId=' + $.getQueryParam('resourceId')+'&id=' + id+'&planId=' + planId+'&type=edit';
            openLayers(title, content);
        }
    }else {
        layer.alert("请选择计划下的培训记录进行编辑！");
        return;
    }
}
function infoRecord(id,planId) {
    var title = '培训记录详情';
    var content = ROOT_PATH + '/train/record/info.shtml?resourceId=' + $.getQueryParam('resourceId')+'&id=' + id+'&planId=' + planId+'&type=info';
    openLayers(title, content);
}
function infoUser(id) {
    var title = '培训人员';
    var content = ROOT_PATH + '/train/record/userList.shtml?resourceId=' + $.getQueryParam('resourceId')+'&id=' + id;
    WindowManager.openLayer({
        type: 2,
        resize: false,
        title: title,
        area: ['900px', '70%'],
        content: content
    });
}

